import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, AxiosInstance } from 'axios'
import { useUserStore } from '@/store/user'
import { useTost } from '@/utils/comps'

const baseURL = import.meta.env.XMOV_APP_BASE_URL

const instance: AxiosInstance = axios.create({
  baseURL,
  timeout: 1000 * 60 * 2,
})

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const { appId, userId } = useUserStore()
    const payload = {
      app_id: appId,
      customer_user_id: userId,
    }
    // Set default payload
    if (['POST', 'PUT'].includes(config.method.toUpperCase())) {
      config.data = Object.assign({}, payload, config.data)
    } else {
      config.params = Object.assign({}, payload, config.params)
    }
    return config
  },
  (error: AxiosError) => Promise.reject(error),
)

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, data } = response
    const { error_code: code, error_reason: msg, data: result } = data
    if (+status >= 200 && +status < 400 && +code === 0) {
      return result
    }
    useTost(msg)
    return Promise.reject(response)
  },
  (error: AxiosError) => Promise.reject(error)
)

export const get: (url: string, config?) => Promise<LooseObject> = (url, config) => instance.get(url, config)

export const post: (url: string, data?, config?) => Promise<LooseObject> = (url, data, config) => instance.post(url, data, config)

export const put: (url: string, data?, config?) => Promise<LooseObject> = (url, data, config) => instance.put(url, data, config)

export default instance
